<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数学练习小游戏</title>
  <style>
    body {
      margin: 0;
      font-family: Arial, sans-serif;
      background-color: #f0f0f0;
      overflow: hidden;
    }
    #game-container {
      position: relative;
      width: 100vw;
      height: 100vh;
      overflow: hidden;
      background-image: url('background.jpg'); /* 背景图片 */
      background-size: cover; /* 图片覆盖整个容器 */
      background-position: center; /* 图片居中 */
    }
    .question {
      position: absolute;
      font-size: 48px; /* 字体变大 */
      font-weight: bold; /* 加粗 */
      color: red; /* 红色字体 */
      background-color: rgba(255, 255, 255, 0.7); /* 半透明白色背景 */
      padding: 15px 30px; /* 增大内边距 */
      border-radius: 20px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
    }
    #score {
      position: absolute;
      top: 10px;
      left: 10px;
      font-size: 20px;
      font-weight: bold;
      color: #fff; /* 得分文字颜色改为白色 */
    }
    #game-over {
      display: none;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
      font-size: 36px;
      font-weight: bold;
      color: #fff; /* 游戏结束文字颜色改为白色 */
    }
    #game-over button {
      margin-top: 20px;
      padding: 10px 20px;
      font-size: 18px;
      cursor: pointer;
      border: none;
      border-radius: 5px;
      background-color: #007bff;
      color: white;
    }
    #game-over button:hover {
      background-color: #0056b3;
    }
    #music-control {
      position: absolute;
      bottom: 10px;
      right: 10px;
      font-size: 16px;
      cursor: pointer;
      color: #fff;
    }
  </style>
</head>
<body>
  <div id="game-container">
    <div id="score">得分: 0</div>
    <div id="game-over">
      <div>Game Over</div>
      <button id="restart-button">重新开始</button>
      <button id="exit-button">退出</button>
    </div>
    <div id="music-control" onclick="toggleMusic()">🎵 暂停音乐</div>
  </div>

  <!-- 背景音乐 -->
  <audio id="background-music" src="background-music.mp3" autoplay loop></audio>

  <script>
    const gameContainer = document.getElementById('game-container');
    const scoreDisplay = document.getElementById('score');
    const gameOverDisplay = document.getElementById('game-over');
    const restartButton = document.getElementById('restart-button');
    const exitButton = document.getElementById('exit-button');
    const musicControl = document.getElementById('music-control');
    const backgroundMusic = document.getElementById('background-music');

    let score = 0;
    let questions = [];
    let recognition;
    let questionInterval;

    // 初始化语音识别
    function initSpeechRecognition() {
      if (!('webkitSpeechRecognition' in window)) {
        alert('您的浏览器不支持语音识别功能，请使用Chrome浏览器！');
        return;
      }

      recognition = new webkitSpeechRecognition();
      recognition.continuous = true;
      recognition.interimResults = false;
      recognition.lang = 'zh-CN';

      recognition.onresult = (event) => {
        const transcript = event.results[event.results.length - 1][0].transcript.trim();
        console.log(transcript);
				// checkAnswer(transcript[transcript.length - 2]);
				checkAnswer(transcript);
      };

      recognition.onerror = (event) => {
        console.error('语音识别错误:', event.error);
      };

      recognition.start();
    }

    // 生成随机题目（20以内加减法，确保不会出现负数）
    function generateQuestion() {
      let num1 = Math.floor(Math.random() * 21); // [0, 20]
      let num2 = Math.floor(Math.random() * 21); // [0, 20]
      const operation = Math.random() < 0.5 ? '+' : '-';

      // 确保减法不会出现负数
      if (operation === '-' && num1 < num2) {
        [num1, num2] = [num2, num1]; // 交换 num1 和 num2
      }

      const answer = operation === '+' ? num1 + num2 : num1 - num2;

      return { question: `${num1} ${operation} ${num2}`, answer };
    }

    // 添加题目到屏幕
    function addQuestion() {
      const { question, answer } = generateQuestion();
      const questionElement = document.createElement('div');
      questionElement.classList.add('question');
      questionElement.textContent = question;
      questionElement.style.left = `${Math.random() * 90}vw`;
      questionElement.style.top = '-100px'; // 初始位置更高
      gameContainer.appendChild(questionElement);

      const speed = Math.random() * 1 + 0.5; // 下落速度变慢
      questions.push({ element: questionElement, answer });

      moveQuestion(questionElement, speed);
    }

    // 移动题目
    function moveQuestion(element, speed) {
      let position = -100;
      const interval = setInterval(() => {
        position += speed;
        element.style.top = `${position}px`;

        if (position > window.innerHeight) {
          clearInterval(interval);
          removeQuestion(element);
          updateScore(-1); // 扣分
        }
      }, 16);

      element.dataset.interval = interval;
    }

    // 移除题目
    function removeQuestion(element) {
      element.remove();
      questions = questions.filter(q => q.element !== element);
    }

    // 检查答案
    function checkAnswer0(answer) {
      const parsedAnswer = parseInt(answer, 10);
      for (let i = 0; i < questions.length; i++) {
        const { element, answer: correctAnswer } = questions[i];
        if (parsedAnswer === correctAnswer) {
          clearInterval(element.dataset.interval);
          explodeQuestion(element);
          updateScore(1); // 加分
          questions.splice(i, 1);
          break;
        }
      }
    }

				// 检查答案
		function checkAnswer(transcript) {
			// 使用正则表达式提取所有数字
			const numbers = transcript.match(/\d+/g); // 匹配所有数字
			if (!numbers || numbers.length < 3) {
				console.log('无法提取足够的数字:', transcript);
				return; // 如果没有提取到至少三个数字，则直接返回
			}

			// 将提取的数字转换为整数
			const num1 = parseInt(numbers[0], 10); // 第一个数字
			const num2 = parseInt(numbers[1], 10); // 第二个数字
			const answer = parseInt(numbers[2], 10); // 第三个数字（玩家的回答）
			console.log(`${num1} ${num2} ${answer}`);

			// 遍历当前题目列表，找到匹配的题目
			for (let i = 0; i < questions.length; i++) {
				const { element, answer: correctAnswer } = questions[i];
				const questionText = element.textContent;

				// 提取题目中的两个数字
    const questionNumbers = questionText.match(/\d+/g);
    if (!questionNumbers || questionNumbers.length < 2) {
      continue; // 如果题目格式不正确，跳过
    }

    const qNum1 = parseInt(questionNumbers[0], 10);
    const qNum2 = parseInt(questionNumbers[1], 10);

    // 判断是否匹配
    if (qNum1 === num1 && qNum2 === num2 && answer === correctAnswer) {
      clearInterval(element.dataset.interval);
      explodeQuestion(element);
      updateScore(1); // 加分
      questions.splice(i, 1);
      break;
    }
  }
}

    // 爆炸效果
    function explodeQuestion(element) {
      element.style.transition = 'transform 0.2s, opacity 0.2s';
      element.style.transform = 'scale(1.5)';
      element.style.opacity = '0';

      setTimeout(() => {
        element.remove();
      }, 200);
    }

    // 更新分数
    function updateScore(delta) {
      score += delta;
      scoreDisplay.textContent = `得分: ${score}`;

      if (score < 0) {
        endGame();
      }
    }

    // 游戏结束
    function endGame() {
      gameOverDisplay.style.display = 'block';
      recognition.stop();

      // 停止生成新题目
      clearInterval(questionInterval);

      // 清空所有题目
      questions.forEach(({ element }) => {
        clearInterval(element.dataset.interval);
        element.remove();
      });

      questions = [];
    }

    // 重新开始游戏
    function restartGame() {
      score = 0;
      scoreDisplay.textContent = `得分: ${score}`;
      gameOverDisplay.style.display = 'none';

      // 重新初始化语音识别和题目生成
      initSpeechRecognition();
      questionInterval = setInterval(addQuestion, 3000); // 每3秒生成一个新题目
    }

    // 切换背景音乐
    function toggleMusic() {
      if (backgroundMusic.paused) {
        backgroundMusic.play();
        musicControl.textContent = '🎵 暂停音乐';
      } else {
        backgroundMusic.pause();
        musicControl.textContent = '🎵 播放音乐';
      }
    }

    // 绑定按钮事件
    restartButton.addEventListener('click', restartGame);
    exitButton.addEventListener('click', () => {
      alert('感谢游玩！再见！');
      window.location.reload(); // 刷新页面退出游戏
    });

    // 开始游戏
    function startGame() {
      initSpeechRecognition();
      questionInterval = setInterval(addQuestion, 3000); // 每3秒生成一个新题目
    }

    startGame();
  </script>
</body>
</html>